<template>
  <ContentField v-if="show_content">
    <div class="row justify-content-md-center">
      <div class="col-3">
        <!-- 提交的时候触发login函数，阻止默认行为 -->
        <form @submit.prevent="login"> 
          <div class="mb-3">
            <label for="username" class="form-label">用户名</label>
            <input v-model="username" type="text" class="form-control" id="username" placeholder="请输入用户名">
            <label for="password" class="form-label">密码</label>
            <input v-model="password" type="password" class="form-control" id="password" placeholder="请输入密码">
            <div class="error-message">{{error_message}}</div>
            <button type="submit" class="btn btn-primary">提交</button>
          </div>
        </form>
      </div>
    </div>
  </ContentField>
</template>

<script>
import ContentField from '@/components/ContentField.vue';
import {ref} from 'vue'
import {useStore} from 'vuex' //全局变量
import router from '@/router/index.js'
export default {
  components: {
    ContentField,
  },
  setup(){
    let username = ref("");
    let password = ref("");
    let error_message = ref("");
    let show_content = ref(false);
    const store = useStore(); //全局变量

    const jwt_token = localStorage.getItem("jwt_token");
    if(jwt_token){ //有jwt_token，说明已经登录了
      store.commit("updateToken",jwt_token); //存储jwt_token
      store.dispatch("getinfo",{ //验证token是否合法
        success(){ //成功就跳转到home页面
          router.push({name:"home"}); 
        },
        error(resp){
          console.log(resp);
          show_content.value = true; //当前token已经过期了
        }
      });
    }else{
      show_content.value = true; //本地没有存储jwt_token
    }
    const login=()=>{
      error_message.value = "";
      store.dispatch("login",{ //调用actions中的login方法
        username:username.value,
        password:password.value,
        success(){      
          store.dispatch("getinfo",{ //调用actions中的getinfo方法
            success(){ 
              router.push({name:"home"}); //跳转到home页面
              console.log(store.state.user);
            },
            error(resp){
              console.log(resp);
            }
          });
        },
        error(resp){
          console.log("error");
          console.log(resp);
          error_message.value = "用户名或密码错误";
        }
      });
    }
    return {
      username,
      password,
      error_message,
      login,
      show_content,
    }  
  }    
}

</script>

<style scoped>
button{
  margin-top: 10px;
  width: 100%;
}
.error-message{
  color: red;
}
</style>